package com.example.jsoup;

import com.example.core.WebItemsCrawler;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.Optional;

public class CaoliuPageListCrawler extends WebItemsCrawler<CaoliuRow> {
    private static final String XPATH = "//tbody[@id='tbody']/tr";

    private String category;

    public CaoliuPageListCrawler(String url) throws IOException {
        super(url, XPATH);
    }

    @Override
    protected void init() {
        if (category != null) {
            return;
        }
        this.category = Optional.of(doc.selectXpath("//tbody/tr/th[@class='h']/a")).map(Elements::first).map(Element::text).orElse("");
    }

    @Override
    protected CaoliuRow parseItem(Element element) {
        Optional<Element> titleElement = Optional.of(element.child(1)).map(x -> x.getElementsByTag("a")).map(Elements::first);
        String id = titleElement.map(x -> x.attribute("id").getValue()).orElse(null);
        String url = titleElement.map(x -> x.attribute("href").getValue()).orElse(null);
        String title = titleElement.map(Element::text).orElse(null);

        Optional<Element> authorElement = Optional.of(element.child(2)).map(x -> x.getElementsByTag("a")).map(Elements::first);
        String author = authorElement.map(Element::text).orElse(null);
        String authorUrl = authorElement.map(x -> x.attribute("href").getValue()).orElse(null);

        String replyCount = element.child(3).text();
        String downloadCount = element.child(4).text();
        String lastReport = element.child(5).text();

        CaoliuRow row = new CaoliuRow();
        row.setCategory(category);
        row.setId(id);
        row.setUrl(url);
        row.setTitle(title);
        row.setAuthor(author);
        row.setAuthorUrl(authorUrl);
        row.setReplyCount(parseInt(replyCount));
        row.setDownloadCount(parseInt(downloadCount));
        row.setLastReport(lastReport);
        return row;
    }

    private int parseInt(String s) {
        if (s == null || s.isBlank()) {
            return 0;
        }
        try {
            return Integer.parseInt(s);
        } catch (Exception e) {
            return 0;
        }
    }
}
